<template>
	<div class="user-box">
		<van-sticky>
			<div class="searchBox">
				<div class="title">黑名单</div>
				<van-search v-model="params.nickname" placeholder="请按用户昵称/用户编码搜索" @search="handleSearch">
					<template #right-icon>
						<div class="search-confirm" @click.stop="handleSearch">
							<span style="margin-right: 10px; height: 24px">|</span>
							<span class="search-text">搜索</span>
						</div>
					</template>
				</van-search>
<!--				<div class="condition">-->
<!--					<van-field v-model="params.startTime" readonly name="datePicker" placeholder="请选择开始时间"-->
<!--						@click="timekai('startTime')" style="width:40%;cursor: pointer;" input-align="center" />-->
<!--					<van-field v-model="params.endTime" readonly name="datePicker" placeholder="请选择结束时间"-->
<!--						@click="timekai('endTime')" style="width:40%;cursor: pointer;" input-align="center" />-->
<!--				</div>-->
			</div>
		</van-sticky>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" finished-text="没有更多数据了"
				:finished="finished" @load="getdata">
				<div style="padding: 10px">
					<div class="grid-content" v-for="(item, index) in list" :key="index" @click="blockUser(item)">
						<span>{{ index + 1 }}</span>
						<div style="margin: 0 14px">
							<van-image round width="50px" height="50px" :src="item.avatar" lazy-load />
						</div>
						<div class="flexcolumn nickname" style="flex: 1">
							<span>{{ item.nickname }}</span>
							<span style="margin-top: 5px">ID:{{ item.id }}</span>
						</div>
						<div class="recharge">累计充值:{{ item.totalRechargeAmount }}</div>
					</div>
				</div>
			</van-list>
		</van-pull-refresh>
	</div>
	<!-- 时间选择 -->
	<van-popup v-model:show="showPicker" destroy-on-close position="bottom" safe-area-inset-bottom round>
		<van-date-picker v-model="currentDate" @confirm="onConfirm" @cancel="showPicker = false" />
	</van-popup>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from "vue";
	import {
		getUserid
	} from "@/utils/auth";
	import {
		deviceCustomerBlackList,
    removeBlacklist
	} from "@/api/vip";
  import {showDialog , showToast} from 'vant';
	// const mark = ref("blacklist");
	// const placeholder = ref("按名称或昵称搜索");

	const params = ref({
		nickname: "",
		size: 10,
		pages: 1,
		userId: getUserid(),
		// startTime: new Date().toISOString().split('T')[0],
		// endTime: new Date().toISOString().split('T')[0],
	});

	const loading = ref(false);
	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);
	const list = reactive([]);

	onMounted(() => {
		getdata();
	});

	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceCustomerBlackList(params.value);
			const records = response.data.records || [];

			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...records);
			} else {
				list.push(...records);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error("获取数据失败", err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
    	params.value.nickname = "";
    	// params.value.startTime = "";
    	// params.value.endTime = "";
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 输入框搜索
	const handleSearch = (item) => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};
	const currentDate = ref([
		new Date().getFullYear().toString(),
		(new Date().getMonth() + 1).toString().padStart(2, '0'),
		new Date().getDate().toString().padStart(2, '0')
	]);
	const showPicker = ref(false);
	const mark = ref("");
	const timekai = (type) => {
		mark.value = type;
		showPicker.value = true;
	};
	const onConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		currentDate.value = selectedValues;
		showPicker.value = false;
		// 身份证有效期
		if (mark.value === 'startTime') {
			params.value.startTime = selectedValues.join('-');
		} else {
			params.value.endTime = selectedValues.join('-');
		}
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	}

	const blockUser = (item) => {
		//console.log(item);
    const params = {
      customerId: item.id
    }
		showDialog({
			title: "提示",
			message: "确定要移除该用户吗?",
			showCancelButton: true,
			keyboardEnabled: false,
		}).then(async () => {
			try {
				const response = await removeBlacklist(params);
				if (response.status == 200) {
					showToast({
						type: "success",
						message: "已移除",
						forbidClick: true,
						duration: 1000,
					});
				} else {
					showToast({
						type: "fail",
						message: response.desc || "移除失败",
						forbidClick: true,
						duration: 1000,
					});
				}
				setTimeout(() => {
					onRefresh();
				}, 1000);
			} catch (err) {
				showToast({
					type: "fail",
					message: err.desc || "移除失败",
					forbidClick: true,
					duration: 1000,
				});
			}
		}).catch(() => {
			// on cancel
		});
	};
</script>

<style scoped lang="scss">
	.searchBox {
		background-color: #fff;
		width: 100%;

		.title {
			text-align: center;
			color: #000;
			padding: 0.5em;
			font-weight: bold;
		}
	}

	:deep(.searchBox) {
		.van-search {
			background-color: white;

			/* 搜索框 */
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				/* border-radius: 5px; */
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2fbc3c;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		/* 文字 */
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}

	.grid-content {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-top: 20px;
		background-color: white;
		padding: 10px;
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-between;
		cursor: pointer;

		.nickname {
			font-size: 12px;
			width: 50%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			color: rgb(147, 147, 147);
		}

		.recharge {
			height: 100%;
			margin-left: 20px;
			font-size: 12px;
			color: rgb(147, 147, 147);
		}
	}

	.flex {
		display: flex;
		align-items: center;
		align-content: center;
	}

	.flexcolumn {
		display: flex;
		flex-direction: column;
	}

	.condition {
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-around;
		gap: 10px;
		padding: 0 10px;
		box-sizing: border-box;

		.conditionLi {
			padding: 6px;
			border-radius: 8px;
			border: 1px solid #ddd;
			font-size: 12px;
			background-color: #FFF;
		}
	}
</style>
